package dbUtil

import (
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var gormDB *gorm.DB

// 定义结构体
// 特别注意：结构体名称为：user，创建的表的名称为：users
type user struct {
	Id         int       `gorm:"primaryKey;autoIncrement" json:"id"` //指定主键并自增
	UserNo     int       `gorm:"unique" json:"user_no"`
	Name       string    `gorm:"type:varchar(256);not null" json:"name"`
	Age        int       `gorm:"type:tinyint(4);not null" json:"age"`
	Address    string    `gorm:"type:varchar(256);not null" json:"address"`
	CreateTime time.Time `json:"create_time"`
	UpdateTime time.Time `json:"update_time"`
}

func init() {
	var err error
	sqlStr := "root:rx123456@tcp(127.0.0.1:3306)/gin_demo?charset=utf8mb4&parseTime=true&loc=Local"
	gormDB, err = gorm.Open(mysql.Open(sqlStr), &gorm.Config{}) //配置项中预设了连接池 ConnPool
	if err != nil {
		fmt.Println("数据库连接出错：", err)
		return
	}
}

// 捕获异常
func catchException(c *gin.Context) {
	err := recover()
	if err != nil {
		showError(c, fmt.Sprint(err))
	}
}

func GormGetUserList(c *gin.Context) {
	defer func() {
		catchException(c)
	}()

	name := c.Query("name")
	myUser := make([]user, 10)
	tx := gormDB.Where("name=?", name).Find(&myUser).Limit(10) //查询到的有可能为多行，所以采用结构体切片
	if tx.Error != nil {
		showError(c, fmt.Sprint(tx.Error))
		return
	}
	showSuccess(c, myUser)
}

func GormGetUserInfo(c *gin.Context) {
	defer func() {
		catchException(c)
	}()

	id := c.Query("id")
	myUser := user{}
	tx := gormDB.Where("id=?", id).First(&myUser)
	if tx.Error != nil {
		showError(c, fmt.Sprint(tx.Error))
		return
	}
	showSuccess(c, myUser)
}

func GormInsertData(c *gin.Context) {
	/*
		//请求参数
		{
			"user_no":1001,
			"name":"张三",
			"age":18,
			"address":"北京昌平"
		}
	*/

	defer func() {
		catchException(c)
	}()

	var myUser user
	err := c.Bind(&myUser)
	if err != nil {
		showError(c, fmt.Sprint(err))
	}
	fmt.Println("myUser", myUser)
	tx := gormDB.Create(&myUser)
	fmt.Println(tx)
	if tx.RowsAffected > 0 {
		showSuccess(c, tx.RowsAffected)
		return
	} else {
		fmt.Printf("insert failed, err:%v\n", err)
		showError(c, fmt.Sprint(tx.Error))
	}
}

func GormUpdateData(c *gin.Context) {
	/*
		//请求参数
		{
		    "id":1,
		    "age":13,
		    "address":"河北"
		}
	*/
	defer func() {
		catchException(c)
	}()

	var myUser user
	err := c.Bind(&myUser)
	if err != nil {
		showError(c, fmt.Sprint(err))
	}
	fmt.Println("myUser", myUser)

	//先查找
	var count int64
	gormDB.Model(&user{}).Where("id=?", myUser.Id).Count(&count)
	if count == 0 {
		showError(c, "数据不存在")
		return
	}
	//再更新
	tx := gormDB.Model(&user{}).Where("id=?", myUser.Id).Updates(&myUser)
	fmt.Println(tx) //打印结果
	if tx.RowsAffected > 0 {
		showSuccess(c, tx.RowsAffected)
	} else {
		showError(c, fmt.Sprint(tx.Error))
	}
}

func GormDeleteData(c *gin.Context) {
	defer func() {
		catchException(c)
	}()

	id := c.Query("id")
	//先查找
	var count int64
	gormDB.Model(&user{}).Where("id=?", id).Count(&count)
	if count == 0 {
		showError(c, "数据不存在")
		return
	}
	//再删除
	tx := gormDB.Where("id=?", id).Delete(&user{})
	fmt.Println(tx) //打印结果
	if tx.RowsAffected > 0 {
		showSuccess(c, tx.RowsAffected)
	} else {
		showError(c, fmt.Sprint(tx.Error))
	}
}
